package com.du.cloud.security.config;

import com.du.cloud.common.base.constant.RedisKeyConstants;
import com.du.cloud.security.component.PermitUrlProperties;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * Desc: 资源服务器配置
 * Author: dushuang
 * Date: 2020/5/28
 **/
@Configuration
@AllArgsConstructor
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private final RedisConnectionFactory redisConnectionFactory;
    private final PermitUrlProperties permitUrl;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry
                registry = http.authorizeRequests();
        // 配置的接口跳过验证
        permitUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());

        registry
                .anyRequest().authenticated()
                .and().csrf().disable();

    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore());
    }

    public TokenStore tokenStore() {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        redisTokenStore.setPrefix(RedisKeyConstants.OAUTH_KEY_PREFIX);
        return redisTokenStore;
    }
}
